﻿var httpReq = null;
plugin.SetFlags(gddPluginFlagNone, gddContentFlagHaveDetails);

var interval = 60;
var plugin_state = 0;//0 - news showing news types ; 1-showing news headlines
var plugin_state_url = "";

utils.setInterval(OnTimer, 1000 * 60 * interval);
var selectedCountryCode = "in";
var selectedCountry = "India";

SetDefaultOptions();

function OnTimer() {
  if(plugin_state==0)
     Show_NewsTypes();
  else{
     FetchAndParse(plugin_state_url);
  }
}


//---- Functions  and Variables to manage the options dialog
//All Countries and codes
// This is a bit clumsy.. but i dont want to spend time on this.. so left like this.
var countries_names = new Array("Argentina","Australia","BelgiÃ«","Belgique","Brasil","Canada English","Canada FranÃ§ais","Chile","Colombia","Cuba","Deutschland","EspaÃ±a","Estados Unidos","France","India","Ireland","Italia","MÃ©xico","Nederland","New Zealand","Ã–sterreich","PerÃº","Portugal","Schweiz","South Africa","Suisse","U.K.","U.S.","Venezuela","China","Hong Kong","Japan","Korea","Taiwan","Israel","Arabic");
var countries_codes = new Array("es_ar","au","nl_be","fr_be","pt-BR_br","ca","fr_ca","es_cl","es_co","es_cu","de","es","es_us","fr","in","en_ie","it","es_mx","nl_nl","nz","de_at","es_pe","pt-PT_pt","de_ch","en_za","fr_ch","uk","us","es_ve","cn","hk","jp","kr","tw","iw_il","ar_me");

plugin.onShowOptionsDlg = ShowOptionsDlg; // handler for options dialog

function SetDefaultOptions() {

  if (options.exists("countrycode")) 
     if(options("countrycode")!=null && options("countrycode")!="")
         selectedCountryCode = options("countrycode");
     else
       options("countrycode")  = selectedCountryCode;
   else
       options("countrycode")  = selectedCountryCode;

   if (options.exists("country")) 
      if(options("country")!=null && options("country")!="")
       selectedCountry = options("country");
   else
       options("country")  = selectedCountry;
   else
       options("country")  = selectedCountry;


}

function GetSelectedCountryCode() {
  var ctr = selectedCountry;
  var i = 0;
  for(i=0;i<countries_names.length;i++){
    if(countries_names[i]==ctr)
     break;
  }
  return countries_codes[i];
}


function ShowOptionsDlg(wnd) {
  wnd.AddControl(gddWndCtrlClassLabel, 0, "", "Country", 10, 10, 280, 30);
  var list = wnd.AddControl(gddWndCtrlClassList, gddWndCtrlTypeListDrop, "country", countries_names, 10, 35, 280, 2000);
  list.value = selectedCountry;
  // handlers
  wnd.onClose = OptionsDlgClosed;
  
}

function OptionsDlgClosed(wnd, code) {
  if (code == gddIdOK) {
    var list = wnd.GetControl("country");
    
    selectedCountry = list.value;
    selectedCountryCode = GetSelectedCountryCode();
    options("countrycode")  = selectedCountryCode;
    options("country") = selectedCountry;
    OnTimer();  // to refresh items and add again
  }
}


//Main View.. All the news types.. 
var newsTypes = ["Top News","World","COUNTRY","Business","Sci/Tech","Health","Sports","Entertainment"];
// Links.. for all the news types
var categoryCodes = ["h","w","n","b","t","m","s","e"];

// function to display the main view.. 
function  Show_NewsTypes()
{
   var NewsTypeItems = new Array();
   
   cnArea.removeAllContentItems();

   for(var newsIndx=newsTypes.length-1;newsIndx>=0;newsIndx--){
      var newsItem = new ContentItem();
      newsItem.onDrawItem = DrawBackground;
      
      newsItem.heading =  newsIndx!=2?newsTypes[newsIndx]:selectedCountry ;
      newsItem.onDetailsView =NewsTypeLink_Clicked;
      newsItem.open_command = "http://news.google.com/news?ned="+selectedCountryCode+"&topic=" + categoryCodes[newsIndx];
      //var url = new String(newsTypesLinks[newsIndx]);
      var url = new String("http://news.google.com/news?ned=[country]&topic=[cat]&output=rss");
      url = url.replace("[cat]", categoryCodes[newsIndx]);
      url = url.replace("[country]",GetSelectedCountryCode());
      newsItem.source = url;
      //newsItem.SetRect(textheight*(newsIndx-1), textheight*newsIndx, plugin.window_width, textheight);
      cnArea.addContentItem(newsItem, gddItemDisplayInSidebar );
   }
   plugin_state = 0;//to preserve plugin state 
}

function DrawBackground(item, target, graphics, x, y, width, height) {
  var bgColor = getNewsBgColor(item.heading);
  graphics.DrawRect(x, y, x+5, height, bgColor, bgColor);
  graphics.DrawText(x+6, y, width, height, "  " + item.heading, gddColorNormalText, 
  gddTextFlagSingleLine + gddTextFlagVCenter, gddFontNormal);
}

//Colored bars.. in the main view before each category.
function getNewsBgColor(heading) {

  var bgColor = "#ffffdd";
  if(heading=="Recommended")
    bgColor = '#aa0033'
  else if(heading=="World")
    bgColor= "#ffcc00";
  else if(heading=="Business")
    bgColor = "#008000";
  else if(heading=="Sci/Tech")
   bgColor = "#cc0000";
  else if(heading=="Sports")
   bgColor = "#ff6600";
  else if(heading=="Entertainment")
   bgColor = "#663399";
  else if(heading=="Health")
   bgColor ="#669999";
  else if(heading=="Most Popular")
    bgColor ="#ff4542";

  return bgColor;
}


// Event listener for Each category link
function NewsTypeLink_Clicked(item) {
   cnArea.cursor = "wait";
   var url = item.source;
   plugin_state=1;
   plugin_state_url = url;//to preserve plugin state 
   FetchAndParse(url);
   
}


//Fetches the Rss feed from the selected site.
function FetchAndParse(url) {
  
  httpReq = new XMLHttpRequest();
  httpReq.onreadystatechange = OnRssFeed;
  httpReq.open("GET", url, true);
  httpReq.send();  
}

function OnRssFeed() {
   if(httpReq.readyState==4){
      if(httpReq.status==200){
         var doc = new DOMDocument();
         doc.loadXML(httpReq.responseText);
         //alert(httpReq.responseText);
         var items = doc.getElementsByTagName("item");
         if(items.length>0) {

	    cnArea.removeAllContentItems();
            cnArea.contentFlags = gddContentFlagHaveDetails;


            for(var i=items.length-1;i>=0;i--){
               //parse the item
               var title, reporter ,link, pubDate, desc;
               for (var node = items[i].firstChild; node != null; node = node.nextSibling) {
                   if (node.nodeName == "title")
                      title = node.firstChild.nodeValue;
                   else 
                   if(node.nodeName== "link")
                      link = node.firstChild.nodeValue;
                   else
                   if(node.nodeName == "pubDate")
                      pubDate = node.firstChild.nodeValue;
                   else
                   if(node.nodeName == "description")
                      desc = node.firstChild.nodeValue;
                }
                   
                var curItem = new ContentItem();
                curItem.layout = gddContentItemLayoutNews;
                curItem.onDetailsView = OnDetailsView;
                cnArea.AddContentItem(curItem, gddItemDisplayInSidebar);
                
                var titleStr = new String(title);

		//removing the html special characters
		// I didnt found any other solution other than this..
                
                titleStr = titleStr.replace(/&#[0-9]+;/g," ");
                titleStr = titleStr.replace(/&quot;/g,"'");
		titleStr = titleStr.replace(/&amp;/g,"&");
                var indx_bar = titleStr.lastIndexOf("-");
                curItem.heading = titleStr.substring(0,indx_bar-1);
                //curItem.source = link;
		curItem.source = titleStr.substring(indx_bar+1, titleStr.length);

                // to show in details view
                curItem.snippet = desc;
              
                var tm = new Date(pubDate);
                tm.setMinutes(tm.getMinutes() + tm.getTimezoneOffset());
                curItem.time_created = tm.getVarDate();
                curItem.open_command = link;//to open the browser
                
            }                
	    //Back link
	    var backToMain = new ContentItem(); 
	    backToMain.heading =  _back2main ;
	    backToMain.onDetailsView = Show_NewsTypes;
	    cnArea.AddContentItem(backToMain, gddItemDisplayInSidebar);
			cnArea.cursor = "arrow";
         }
      }
   }
}

//Details view handler. Formats the html code and displays
function OnDetailsView(item) {
  
  var htmlcontent = "<html><head></head><body>";
  htmlcontent += item.snippet;
  htmlcontent += "</body></html>";
  
  var control = new DetailsView();
 
  control.SetContent(item.source, item.time_created, htmlcontent, true, item.layout);
  control.html_content = true;

  var details = new Object();
  details.details_control = control;
  
  return details;
}
